package com.example.demo.Service.lmp;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.Dto.CreditDto;
import com.example.demo.Dto.CreditGetDto;
import com.example.demo.Mapper.CreditMapper;
import com.example.demo.Service.CreditService;

import com.example.demo.Util.ThreadLocallUtil;
import com.example.demo.VO.CreditVo;
import com.example.demo.po.Credit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class CreditServiceImp  extends ServiceImpl<CreditMapper, Credit> implements CreditService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    @Transactional
    public CreditVo saveCredit(CreditDto creditDto) {
        Credit bean = BeanUtil.toBean(creditDto, Credit.class);
        bean.setUserId(ThreadLocallUtil.getUser().getUserId());
        bean.setExpire_date(LocalDate.now().plusDays(365));
        bean.setDeleted(0);
        bean.setStatus(0);
        bean.setCreate_time(LocalDateTime.now());
        bean.setUpdate_time(LocalDateTime.now());
        if (!(save(bean))){
            throw new RuntimeException("添加失败");
        }
        return BeanUtil.toBean(bean, CreditVo.class);
    }

    @Override
    @Transactional
    public void deletebyId(CreditGetDto id) {
      if (!(removeById(id.getCreditNumber()))){
          throw new RuntimeException("删除失败");
      }
      redisTemplate.opsForValue().getAndDelete("credit:"+id.getCreditNumber());
    }

    @Override
    public CreditVo getCredit(String cardNumber) {
        Object o = redisTemplate.opsForValue().get("credit:" + cardNumber);
        if (o != null){
            o=(Credit)o;
            return BeanUtil.toBean(o, CreditVo.class);
        }
        Credit byId = getById(cardNumber);
        if (byId ==null){
           throw new RuntimeException("银行卡不存在");
       }
        redisTemplate.opsForValue().set("credit:"+cardNumber,byId);
        return BeanUtil.toBean(byId, CreditVo.class);
    }

    @Override
    public IPage<CreditVo> getCreditBysize(Integer pageNum, Integer pageSize) {
        Page<Credit> objectPage = new Page<>(pageNum, pageSize);
        Page<Credit> page = lambdaQuery().eq(Credit::getUserId, ThreadLocallUtil.getUser().getUserId())
                .page(objectPage);
        Page<Credit> page1 = query().page(page);
        IPage<CreditVo> page2 = (Page<CreditVo>) page1.convert(item -> BeanUtil.toBean(item, CreditVo.class));
        return page2;
    }
}
